package com.fanketly.musicdiary.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.rememberAsyncImagePainter
import com.fanketly.musicdiary.R
import com.fanketly.musicdiary.data.model.DiaryModel
import com.fanketly.musicdiary.data.model.isMusicNotEmpty
import com.fanketly.musicdiary.data.moodMap
import com.fanketly.musicdiary.domain.MusicViewModel
import com.fanketly.musicdiary.ui.theme.*
import com.fanketly.musicdiary.utls.MoodUtils
import kotlinx.coroutines.launch


@Composable
fun DiaryList(
    list: List<DiaryModel>,
    onClick: (diary: DiaryModel) -> Unit
) {
    Surface(
//        Modifier.statusBarsPadding(),
        color = BlackBackgroundColor,
        contentColor = TextDeepBlack
    ) {
        CommonList(list = list, key = { it.id }) { item ->
            DiaryCardItem(
                diaryModel = item,
                modifier = Modifier
                    .padding(
                        start = LargeDimen,
                        end = LargeDimen,
                        top = MediumDimen,
                        bottom = MediumDimen
                    )
                    .fillMaxWidth()
                    .clickableCustomIndication(onClick = { onClick.invoke(item) })
            )
            Divider(
                Modifier
                    .padding(
                        start = LargeDimen,
                        end = LargeDimen,
                    ), color = H2Color
            )
        }
    }
}

@Composable
fun DiaryCardItem(
    modifier: Modifier,
    diaryModel: DiaryModel,
    viewModel: MusicViewModel = hiltViewModel()
) {
    Surface(modifier = modifier, color = BlackBackgroundColor) {
        Column {
            Row(verticalAlignment = Alignment.CenterVertically) {
                moodMap[diaryModel.mood]?.image.let {
                    if (it != null) Image(
                        modifier = Modifier
                            .size(48.dp)
                            .padding(SmallDimen)
                            .clip(CircleShape),
                        painter = painterResource(id = it),
                        contentDescription = null,
                    )
                    else Spacer(
                        modifier = Modifier
                            .size(48.dp)
                            .padding(SmallDimen)
                    )
                }
                Column(Modifier.padding(start = SmallDimen)) {
                    Text(
                        style = MaterialTheme.typography.h2,
                        fontWeight = FontWeight.Bold,
                        fontSize = 18.sp,
                        color = TextWhite,
                        text = "${diaryModel.month}-${diaryModel.dayOfMonth}"
                    )
                    Text(
                        style = MaterialTheme.typography.subtitle2,
                        color = H2Color,
                        fontSize = 16.sp,
//                        fontFamily = FontFamily(Font(R.font.himelody_regular)),
                        text = diaryModel.mood
                    )
                }
                Spacer(modifier = Modifier.weight(1f))
                if (diaryModel.isMusicNotEmpty()) Icon(
                    imageVector = Icons.Filled.MusicNote,
                    modifier = Modifier
                        .size(36.dp)
                        .padding(end = MediumDimen)
                        .clickableCustomIndication() {
                            viewModel.playMusicByID(diaryModel.musicID!!)
                        },
                    tint = ImageColor,
                    contentDescription = "music"
                )
            }
            if (diaryModel.imgPath.isNotEmpty()) Image(
                modifier = Modifier
                    .padding(top = SmallDimen)
                    .fillMaxWidth()
                    .height(200.dp),
                contentScale = ContentScale.Crop,
                painter = rememberAsyncImagePainter(diaryModel.imgPath),
                contentDescription = null
            )
//                Image(
//                    modifier = Modifier
////                        .padding(top = SmallDimen)
//                        .fillMaxWidth()
//                        .height(200.dp),
//                    painter = rememberAsyncImagePainter(R.drawable.jay_music_album_photo),
//                    contentDescription = null
//                )
            Text(
                style = MaterialTheme.typography.subtitle2,
                fontSize = 16.sp,
//                fontFamily = FontFamily(Font(R.font.himelody_regular)),
                color = TextWhite,
                text = diaryModel.content,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.padding(MediumDimen)
            )

        }
    }
}

@OptIn(ExperimentalUnitApi::class)
@Composable
fun DiaryDetail(
    diaryModel: DiaryModel,
    imagePath: MutableState<String>,
    onUpdateClick: (newDiary: DiaryModel) -> Unit,
    onImageClick: () -> Unit,
    onBackClick: (() -> Unit)? = null,
    musicViewModel: MusicViewModel = hiltViewModel()
) {
    val scope = rememberCoroutineScope()
    val isEdited = remember { mutableStateOf(false) }//DETERMINE IF EDITED
    val text = remember { mutableStateOf(diaryModel.content) }//record the content of the input box
    LaunchedEffect(imagePath.value) {//If the picture has changed, it is edited
        isEdited.value = imagePath.value != diaryModel.imgPath
//        Log.i(TAG, "DiaryDetail_imagePath:${imagePath.value} ")
    }
    var offsetY by remember {
        mutableStateOf(30f)
    }
    val boxSideLengthDp = 1.dp
    val boxSlideLengthPx = with(LocalDensity.current) {
        boxSideLengthDp.toPx()
    }
    val maxValue = -200 * boxSlideLengthPx
    val draggableState = rememberDraggableState {
        offsetY = (offsetY + it).coerceIn(maxValue, 30f)
    }
    Surface {
        ConstraintLayout(
            Modifier
                .fillMaxSize()
                .background(BlackBackgroundColor)
        ) {
            val (imageBox, textField) = createRefs()
            Box(
                modifier = Modifier
                    .constrainAs(imageBox) {
                        top.linkTo(parent.top)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                        width = Dimension.fillToConstraints
                    }
                    .fillMaxHeight(0.4f)
            ) {
                //TOP IMAGE
                Image(
                    painter = rememberAsyncImagePainter(
                        model = imagePath.value.ifEmpty { R.drawable.ic_baseline_add_a_photo_56 }
                    ),
                    contentDescription = stringResource(id = R.string.description_photo),
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .fillMaxSize(if (imagePath.value.isEmpty()) 0.3f else 1f)
                        .align(Alignment.Center)
                        .clickable {
                            onImageClick.invoke()
                        }
                )
                //Back button, judge whether to add or not according to whether it is the page that is swiped left on the home page
                if (onBackClick != null) Icon(
                    imageVector = Icons.Filled.ArrowBack,
                    contentDescription = stringResource(id = R.string.description_mood),
                    modifier = Modifier
                        .padding(start = LargeDimen, top = SmallDimen)
                        .statusBarsPadding()
                        .size(32.dp)
                        .alpha(0.7f)
                        .clip(CircleShape)
                        .background(TextWhite)
                        .clickable {
                            onBackClick.invoke()
                        }
                )
                //Components in the lower right corner of the picture
                Box(
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .padding(bottom = MediumDimen)
                        .height(48.dp)
                        .fillMaxWidth(0.7f)
                ) {
                    //date and music
                    Row(
                        Modifier
                            .fillMaxSize()
                            .padding(start = 24.dp)
                            .background(BlackBottomBackground),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Text(
                            text = "${diaryModel.month}-${diaryModel.dayOfMonth}",
                            color = TextWhite,
                            fontSize = 18.sp,
                            modifier = Modifier
                                .weight(1f)
                                .padding(start = 36.dp)
                        )
                        if (diaryModel.isMusicNotEmpty()) Icon(
                            imageVector = Icons.Filled.MusicNote,
                            modifier = Modifier
                                .padding(end = MediumDimen)
                                .size(36.dp)
                                .clickableCustomIndication {
                                    musicViewModel.playMusicByID(diaryModel.musicID!!)
                                },
                            tint = ImageColor,
                            contentDescription = "music"
                        )
                    }
                    //Update
                    if (isEdited.value) Icon(
                        imageVector = Icons.Filled.Check,
                        contentDescription = stringResource(id = R.string.description_save),
                        tint = TextWhite,
                        modifier = Modifier
                            .size(48.dp)
//                            .clip(CircleShape)
                            .shadow(3.dp, RoundedCornerShape(50))
                            .background(SecondaryColor)
                            .clickable() {
                                //保存
                                scope.launch {
                                    isEdited.value = false
                                    val t = text.value
                                    val mood = MoodUtils.guessMood(t)
                                    onUpdateClick.invoke(
                                        diaryModel.copy(
                                            content = t,
                                            mood = mood,
                                            imgPath = imagePath.value,
                                            musicID = if (mood.isNotEmpty()) musicViewModel.updateMusic(
                                                mood
                                            ) else null
                                        )
                                    )
                                }
                            }
                    )//Mood
                    else moodMap[diaryModel.mood]?.let {
                        Image(
                            painter = painterResource(id = it.image),
                            contentDescription = stringResource(id = R.string.description_mood),
                            modifier = Modifier
                                .size(48.dp)
                                .shadow(3.dp, RoundedCornerShape(50))
                                .background(BlackBottomBackground)
                        )
                    }
                }
            }
            /**INPUT CODE AREA**/
            Surface(
                Modifier
                    .draggable(orientation = Orientation.Vertical, state = draggableState)
                    .constrainAs(textField) {
                        top.linkTo(imageBox.bottom, margin = (offsetY / boxSlideLengthPx).dp)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                        bottom.linkTo(parent.bottom)
                        width = Dimension.fillToConstraints
                        height = Dimension.fillToConstraints
                    },
                shape = RoundedCornerShape(topStart = 30.dp, topEnd = 30.dp),
                color = BlackBottomBackground,
                elevation = 5.dp
            ) {
                TextField(
                    value = text.value,
                    onValueChange = {
                        text.value = it
                        if (!isEdited.value) isEdited.value = true
                    },
                    placeholder = {
                        Text(
                            text = stringResource(id = R.string.diary_content),
                            color = TextWhite
                        )
                    },
                    modifier = Modifier
                        .focusable()
                        .padding(20.dp),
                    textStyle = TextStyle(
                        fontSize = 20.sp,
                    ),
                    colors = TextFieldDefaults.textFieldColors(
                        textColor = TextWhite,
                        backgroundColor = BlackBottomBackground,
                        focusedIndicatorColor = BlackBottomBackground,
                        unfocusedIndicatorColor = BlackBottomBackground
                    )
                )

            }
        }
    }
}



